const ExcelJS = require('exceljs')
const fs = require('fs')
const path = require('path')
const dialog = require('electron').dialog
import FormatValidation from '../rules/index'

export default {
  getExcelData(filePath) {
    // console.log('filePath', filePath)
    const workbook = new ExcelJS.Workbook()
    return new Promise((resolve, reject) => {
      workbook.xlsx
        .readFile(filePath)
        .then(() => {
          // 读取工作表数据
          resolve({ code: 200, msg: '文件读取成功', data: workbook.worksheets })
        })
        .catch((err) => {
          console.log('文件读取失败', err)
          reject({ code: 400, msg: '文件读取失败' })
        })
    })
  },
  checkExcelFile(filePath) {
    return new Promise((resolve) => {
      // 为检测文件扩展名虚假修改，进行文件内容预读
      fs.readFile(filePath, { encoding: null }, (err, fileData) => {
        if (err) {
          resolve({
            code: 400,
            msg: '文件读取失败'
          })
          return
        }
        // 如果文件头部匹配XML的字节，则认为是XML文件
        if (fileData.toString('utf8', 0, 5) === '<?xml') {
          const filename = path.basename(filePath)
          resolve({
            code: 200,
            msg: '读取文件为XML文件',
            data: [
              {
                fileName: filename,
                sheetName: '全局',
                tableType: '全局',
                checkPlace: '全局',
                ruleId: 'FSSJY00046',
                errorInfo:
                  '文件[' +
                  filename +
                  ']的隐藏格式为xml，系统无法识别，请将文件另存为xls/xlsx格式重新上传'
              }
            ]
          })
        } else {
          this.getExcelData(filePath)
            .then((res) => {
              // 格式校验
              const formatValidation = new FormatValidation(res.data, path.basename(filePath))
              // 读取工作表数据
              resolve({
                code: 200,
                msg: '分析完成',
                data: formatValidation.getResult()
              })
            })
            .catch((err) => {
              console.log('读取Excel文件失败', err)
              resolve({
                code: 400,
                msg: '非XLS/XLSX格式文件，或文件已破损!'
              })
            })
        }
      })
    })
  },
  saveExcelFile(excelData) {
    const workbook = new ExcelJS.Workbook()
    const sheet = workbook.addWorksheet('检查结果导出')
    const columns = [
      { header: '所在EXCEL表名', key: 'fileName', width: 20 },
      { header: 'sheet名', key: 'sheetName', width: 20 },
      { header: '校验数据表', key: 'tableType', width: 20 },
      { header: '校验位置', key: 'checkPlace', width: 20 },
      { header: '规则编号', key: 'ruleId', width: 20 },
      { header: '报错反馈', key: 'errorInfo', width: 60 }
    ]
    sheet.columns = columns
    sheet.getRow(1).eachCell((cell) => {
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: '305496' }
      }
      cell.font = { bold: true, color: { argb: 'FFFFFF' } }
    })
    excelData.forEach((excelDatum) => {
      sheet.addRow(excelDatum)
    })
    sheet.eachRow((row) => {
      row.eachCell((cell) => {
        cell.border = {
          top: { style: 'thin' },
          left: { style: 'thin' },
          bottom: { style: 'thin' },
          right: { style: 'thin' }
        }
      })
    })
    const options = {
      filters: [
        {
          name: 'Excel文件',
          extensions: ['xlsx']
        }
      ],
      title: '导出到'
    }
    return new Promise((resolve) => {
      dialog
        .showSaveDialog(options)
        .then((result) => {
          if (!result.canceled)
            workbook.xlsx
              .writeFile(result.filePath)
              .then(() => {
                resolve({ code: 200, msg: '文件保存成功！' })
              })
              .catch((err) => {
                console.log('保存Excel错误', err)
                resolve({ code: 400, msg: '文件保存失败！如覆盖文件请查看文件是否打开！' })
              })
        })
        .catch((err) => {
          console.log('保存Excel错误', err)
          resolve({ code: 400, msg: '文件保存失败！如覆盖文件请查看文件是否打开！' })
        })
    })
  }
}
